# -*- coding: utf-8 -*-
'''
| @author: olivia.dou
| Created on: 2019/11/21 14:07
| desc: 模型元素相关功能
'''
import requests,logging,traceback
from jsonpath import jsonpath
import base.globalvars as glo
from base.getdata import get_header
from util.db_util import execute_query
from util.collection_util import random_select_from_list
from proj_spec.DAS.model import get_model_id


def get_random_model_element_attributes(n=1):
    """
    .. deprecated:: 1.0

    随机获取n个模型元素属性id"""
    sql = "select id from t_das_attribute"
    res = execute_query(sql)
    attribute_ids = [item[0] for item in res]
    attribute_ids = random_select_from_list(attribute_ids,n)
    return attribute_ids

def get_random_model_element_attributes_str(n=1):
    """
    .. deprecated:: 1.0
    """
    attribute_ids = get_random_model_element_attributes(n)
    attribute_ids_str =  ','.join([str(id) for id in attribute_ids])
    glo.set_value("attribute_ids_str",attribute_ids_str)
    return attribute_ids_str

def get_element_info(**kwargs) -> dict:
    """获取模型元素信息

    :param kwargs:
        | element_id: 元素id
        | element_name: 元素名称

    :return: 模型元素信息的字典
    """
    if "element_id" in kwargs:
        element_id = kwargs['element_id']
        field_name = "id"
        value = element_id
    elif "element_name" in kwargs:
        element_name = kwargs['element_name']
        field_name = "element_name"
        value = element_name
    else:
        logging.error("get_element_info error: 未指定element_id/element_name")
        return {}

    """根据元素id获取元素信息"""
    # 使用pymysql 字典方式获取结果
    sql = "select * from t_das_model_element where %s=%s"%(field_name,value)
    res = execute_query(sql, result_type="dict")

    return res[0]

def get_element_attributes(**kwargs):
    """
    .. deprecated:: 1.0

    获取指定模型元素的元素属性
    """

    if "element_id" in kwargs:
        element_id = kwargs['element_id']
    elif "element_name" in kwargs:
        element_id = get_element_info(**kwargs)['id']
    else:
        logging.error("get_element_attributes error: 未指定element_id/element_name")
        return []

    sql = "select attribute_id from t_das_element_attribute where element_id=%s"%element_id
    res = execute_query(sql)
    ids = [item[0] for item in res]
    return ids

def get_element_mapped_biz(element_id):
    """获取指定元素映射的业务

    :param element_id: 元素id

    :return: 元素映射业务的client_code, 业务编码
    """

    sql = """select b.client_code, b.biz_code from t_das_std_biz b inner join t_das_std_biz_element m 
            on m.biz_code = b.biz_code and m.client_code = b.client_code
            where m.element_id=%s
          """%element_id
    res = execute_query(sql)
    return res[0]

def add_model_element(model_id,element_name,source_element_info):
    """添加模型元素
    通过批量更新添加，由于原有模型元素无法全部清空，在调用此方法前先设置一个名字为时间戳格式，描述为'初始元素'的元素
    调用此方法时若模型仅有一个描述为'初始元素'的元素，则修改该元素，否则添加（获取当前所有元素信息，再拼接上新增元素的信息）

    :param model_id: 模型id
    :param element_name: 元素名称
    :param source_element_info: 元素信息的字典

    :return: 无
    """

    from base.get_config import get_header_file
    header1 = get_header(get_header_file(), "header1")
    header2 = get_header(get_header_file(),"header2")

    get_element_info_url = glo.get_value("url2") + "/api/v1/ex/ModelElementEx/filter-with-attributes/%s"%model_id
    res = requests.get(get_element_info_url,headers = header1)
    assert res.status_code==200
    # 判断当前是否仅一个元素且描述为初始元素
    res_json=res.json()
    num_elements  = len(jsonpath(res_json,"$[*]"))
    set_element_url = glo.get_value("url1") + "/api/v1/ModelElement/many/%s"%model_id
    if num_elements==1 and jsonpath(res_json,"$[*].description")[0]=='初始元素':
        #更新元素
        payload = res_json
        payload[0]['elementName']=element_name
        payload[0]['description'] = element_name
        payload[0]['attributeIds'] = source_element_info['attribute_ids']
        payload[0]['algoId'] = source_element_info['algo_id']
        payload[0]['algoInputType'] = source_element_info['algo_input_type']
        payload[0]['elementType'] = source_element_info['element_type']
        payload[0]['keyword'] = source_element_info['keyword']
        res = requests.put(set_element_url,headers=header2,json=payload)
        assert res.status_code==200
    else: #新建元素
        payload = res_json
        new_element = {"attributeIds":source_element_info['attribute_ids'],
                "modelId":model_id,
                "keyword":source_element_info['keyword'],
                "algoId":source_element_info['algo_id'],
                "elementName":element_name,
                "elementType":source_element_info['element_type'],
                "description":element_name,
                "algoInputType":source_element_info['algo_input_type']
                }
        payload.append(new_element)

def get_element_name(element_id):
    """更加元素id获取元素名称

    :param element_id: 元素id

    :return: 元素名称
    """
    sql = "select element_name from t_das_model_element where id=%s"%element_id
    try:
        res = execute_query(sql)
        return res[0][0]
    except Exception as e:
        logging.error(e)
        traceback.print_exc()
        return ""

def get_element_id(model_name, element_name):
    """ 获取元素id

    :param model_name: 模型id
    :param element_name: 元素名称
元素id
    :return:
    """
    model_id = get_model_id(model_name)
    sql = "select id from t_das_model_element where model_id='%s' and element_name='%s'" % (model_id, element_name)
    try:
        res = execute_query(sql)
        return res[0][0]
    except Exception as e:
        return -1


def get_review_element_ids(model_id, file_id, status):
    """ 获取标准化已审核/未审核的元素id

    :param model_id: 模型ID
    :param file_id: 文件ID
    :param status: 0/1 未审核、已审核

    :return: 元素id
    """

    sql = "select element_id from t_das_std_review_status WHERE model_id = %s and file_id = %s and status = %s" % (model_id, file_id, status)
    try:
        res = execute_query(sql)
        return [i[0] for i in res]
    except Exception as e:
        logging.error("get_review_element_ids ：%s" % e)